<template>
  <div class="cardDiv">

      <i class="el-icon-circle-close closeIcon" @click="closeIconFN"></i>
    <el-upload
      class="avatar-uploader"
      action="#"
      :show-file-list="false"
      :http-request="upload"
    >

      <img v-if="imageUrl" :src="imageUrl || imageUrlEdit" class="avatar" />
      <i v-else class=" avatar-uploader-icon uploadText">上传文件</i>

    </el-upload>
  </div>
</template>

<script>
// 导入 cos 模块
const COS = require('cos-js-sdk-v5')
var cos = new COS({
  SecretId: 'AKIDxkGWVEfpiKgT0GGzQaU7TYMuBAsJUP4T',
  SecretKey: '91cx2rQjlW1FDvNZU8VbPyGI2WjfKo1K'
})
export default {
  name: 'imageUpload',
  props: {
    imageUrlEdit: {
      type: String,
      required: false,
      default: ''
    }
  },
  data () {
    return {
      imageUrl: '',
      imageName: ''
    }
  },
  methods: {
    // 编辑回显image图片的方法
    setimageUrl (url) {
      this.imageUrl = url
    },

    // 上传方法
    upload (file) {
      if (file.file) {
        cos.putObject({
          Bucket: 'lele-1308159361', // 存储桶的名称，必须
          Region: 'ap-nanjing', // 存储桶所在地域，必须字段
          Key: file.file.name, // 文件名，必须
          StorageClass: 'STANDARD', // 上传模式, 标准模式
          Body: file.file, // 上传文件对象
          onProgress: function (progressData) {
            // console.log(JSON.stringify(progressData))
          }
        }, (err, data) => {
          if (err === null && data.statusCode === 200) {
            this.imageUrl = `https:${data.Location}`
            this.$emit('imageUploadEvent', this.imageUrl)
          }
        })
        this.imageName = file.file.name
      }
    },

    // 删除对象
    deletImageFn (imageName) {
      cos.deleteObject({
        Bucket: 'lele-1308159361', /* 必须 */
        Region: 'COS_REGION', /* 存储桶所在地域，必须字段 */
        Key: imageName /* 必须 */
      }, function (err, data) {
        console.log(err || data)
      })
    },

    // 点击叉号
    closeIconFN () {
      this.imageUrl = ''
      this.deletImageFn(this.imageName)
      this.$emit('imageUploadEvent', this.imageUrl)
    }
  }
}
</script>

<style scoped>
.closeIcon{
  font-size: 18px;
  color: #999999;
  position: absolute;
  top: -9px;
  right: -9px;
}
.avatar-uploader {
    text-align: center;
}
.uploadText{
   font-style:normal;

}
i.avatar-uploader-icon.uploadText {
    font-size: 14px;
    color: #000;
}
.cardDiv {
  width: 100px;
  height: 60px;
  display: inline-block;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;

}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 60px;
  line-height: 60px;
  text-align: center;
}
.avatar {
  width: 100px;
  height: 60px;
  display: inline-block;
}
</style>
